<template>
  <nav-back title="修改个人信息" />
  <div class="form-box">
    <van-cell-group inset>
      <van-field label="用户名" label-width="60px" v-model="state.username" />
      <van-field label="用户头像" label-width="60px">
        <template #input>
          <van-uploader
            max-count="1"
            :after-read="upload"
            v-model="state.fileList"
          />
        </template>
      </van-field>
    </van-cell-group>

    <div style="margin: 20px 40px">
      <van-button
        @click="submit"
        :loading="state.submitLoading"
        loading-text="处理中..."
        round
        block
        type="primary"
      >
        修改信息
      </van-button>
    </div>
  </div>
</template>

<script setup>
import NavBack from "../components/NavBack.vue";
import { reactive, onBeforeMount } from "vue";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import api from "../api";
import { Toast } from "vant";

const router = useRouter(),
  route = useRoute(),
  store = useStore();

let state = reactive({
  username: "",
  file: null,
  submitLoading: false,
  fileList: [],
});

onBeforeMount(() => {
  let { name, pic } = store.state.info;
  state.username = name;
  // state.fileList = [{ url: pic }];
});

const upload = (result) => {
  state.file = result.file;
};

const submit = async () => {
  let { username, file } = state;
  if (!username || !file) {
    Toast.fail("有未填写的内容!");
    return;
  }
  try {
    state.submitLoading = true;
    let { code } = await api.setUserUpdate(username, file);
    if (+code !== 0) {
      Toast.fail("操作失败!");
      state.submitLoading = false;
      return;
    }
    Toast.success("操作成功!");
    state.submitLoading = false;
    await store.dispatch("setInfoAsync");
    router.go(-1);
  } catch (_) {}
};
</script>

<style lang="less" scoped>
.form-box {
  margin-top: 30px;
}
</style>